package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.DynamicConfigLab;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.ProjectCollectOriginal;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.ToastUtil;

public abstract class TravelReimburselFragment extends Fragment {
  //	protected static final String EXTRA_CONTRACT="com.isunland.managesystem.ui.TravelReimburselFragment.EXTRA_CONTRACT";
  //	/** 判断是订单、合同、项目 */
  //	protected static final String EXTRA_TYPE="com.isunland.managesystem.ui.TravelReimburselFragment.EXTRA_TYPE";
  //	protected static final String ORDER="ORDER";
  //	protected static final String CONTRACT="CONTRACT";
  //	protected static final String PROJECT="PROJECT";
  private String type = "";
  /** 选择合同 */
  protected static final int REQUEST_CONTRACT = 0;//相关合同、订单、项目
  private static final int REQUEST_ADDEXTRA = 1;//附件
  protected static final int REQUEST_RENAME = 2;//重命名
  protected static final int REQUEST_KIND = 3;//费用归属分类
  protected static final int REQUEST_OBJECT = 4;//归属对象
  protected static final int SAVE = 5;//添加保存
  protected static final int SAVE_START = 6;//添加 保存并启动流程
  protected static final String DICTFLG_KIND = "oaFownerKind";//费用归属分类标志
  protected BaseVolleyActivity mActivity;
  protected CurrentUser mCurrentUser;
  protected TextView tvcertificateNo;
  protected EditText etexpenseDesc;
  protected EditText etpoutAmount;
  protected EditText etoffBorrow;
  protected TextView tvsumBorrow;
  protected EditText ettoutAmount;
  protected TextView tvcontractId;
  protected TextView tvregStaffName;
  protected TextView tvapplicantName;
  protected TextView tvapplyTime;
  protected RadioGroup rgisOffest;
  protected RadioButton rbtrueOffset;
  protected RadioButton rbfalseOffset;
  protected ImageView ibcontract;
  //票据
  //	protected TextView tvsumPrebill;
  ////	protected EditText etbillNo;
  //	protected EditText etbillAmount;
  //	protected TextView tvreplenishAmount;
  //	protected EditText etnobillAmount;
  //	protected EditText etbillAmount;//票据费用合计
  protected TextView etbillAmount;//票据费用合计
  //	protected EditText etdeductionAmount;//冲抵预存票合计

  protected EditText etpayeeBank;
  protected EditText etpayeeAccname;
  protected EditText etpayeeAccount;
  /*费用归属*/
  protected TextView tvfownerkindName;//分类
  protected ImageView ibfownerkindName;
  protected TextView tvappobjectName;//对象
  protected ImageView ibappobjectName;//对象

  protected TextView mTvExtra;//附件
  protected ImageView mIvExtra;//附件
  protected String selcurFile = "";//文件上传服务器返回路径
  protected String mFilePath = "";//文件本地路径
  protected String id = "";
  protected String mfileName = "";

  protected String tag;
  protected String TRUE = "T";
  protected String FALSE = "F";
  protected String mContractId = "";//合同id

  protected String mContractName = "";//合同名称
  protected String mContractKind = "";//合同类别
  protected String mContractCode = "";//合同编码
  protected String mContractPrice = "";//合同金额
  protected String mOrderId = "";//订单id
  protected String mOrderName = "";//订单名称
  protected String mOrderType = "";//订单类别
  protected String mProjectId = "";//项目id
  protected String mProjectName = "";//项目名称

  protected String fownerkindName = "";//费用归属分类name
  protected String fownerkindCode = "";//费用归属分类code
  protected String appobjectName = "";//费用归属对象name
  protected String appobjectCode = "";//费用归属对象code

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    if (NavUtils.getParentActivityName(getActivity()) != null) {
      ((BaseVolleyActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    mActivity = (BaseVolleyActivity) getActivity();
    mCurrentUser = CurrentUser.newInstance(getActivity());
    /* 默认归属分类和对象 */
    fownerkindName = "公司费用";
    fownerkindCode = "01";
    appobjectName = mCurrentUser.getMemberName();
    appobjectCode = mCurrentUser.getMemberCode();
    setTitle();
    super.onCreate(savedInstanceState);
  }

  //设置标题
  protected abstract void setTitle();

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_travel_reimburse_detail, container, false);
    tvcertificateNo = (TextView) v.findViewById(R.id.tv_certificateNo);
    tvsumBorrow = (TextView) v.findViewById(R.id.tv_sumBorrow);
    tvcontractId = (TextView) v.findViewById(R.id.tv_contractId);
    tvregStaffName = (TextView) v.findViewById(R.id.tv_regStaffName);
    tvapplicantName = (TextView) v.findViewById(R.id.tv_applicantName);
    tvapplyTime = (TextView) v.findViewById(R.id.tv_applyTime);

    etexpenseDesc = (EditText) v.findViewById(R.id.et_expenseDesc);
    etpoutAmount = (EditText) v.findViewById(R.id.et_poutAmount);
    etoffBorrow = (EditText) v.findViewById(R.id.et_offBorrow);
    ettoutAmount = (EditText) v.findViewById(R.id.et_toutAmount);
    ibcontract = (ImageView) v.findViewById(R.id.ib_contract);

    //票据
    //		tvsumPrebill=(TextView) v.findViewById(R.id.tv_sumPrebill);
    ////		etbillNo=(EditText) v.findViewById(R.id.et_billNo);
    //		etnobillAmount=(EditText) v.findViewById(R.id.et_nobillAmount);
    //		tvreplenishAmount=(TextView) v.findViewById(R.id.tv_replenishAmount);

    etbillAmount = (TextView) v.findViewById(R.id.et_billAmount);//票据费用合计
    //		etdeductionAmount=(EditText) v.findViewById(R.id.et_deductionAmount);//冲抵预存票合计

    etpayeeBank = (EditText) v.findViewById(R.id.et_payeeBank);
    etpayeeAccname = (EditText) v.findViewById(R.id.et_payeeAccname);
    etpayeeAccount = (EditText) v.findViewById(R.id.et_payeeAccount);
		/* 费用分类*/
    tvfownerkindName = (TextView) v.findViewById(R.id.tv_fownerkindName);
    ibfownerkindName = (ImageView) v.findViewById(R.id.ib_fownerkindName);
    tvappobjectName = (TextView) v.findViewById(R.id.tv_appobjectName);
    ibappobjectName = (ImageView) v.findViewById(R.id.ib_appobjectName);

    //RadioButton点击事件，是否冲抵借款
    rgisOffest = (RadioGroup) v.findViewById(R.id.rg_isOffset);
    rbfalseOffset = (RadioButton) v.findViewById(R.id.rb_false_offset);
    rbtrueOffset = (RadioButton) v.findViewById(R.id.rb_true_offset);
    //动态配置列   ---隐藏和显示，title
    DynamicConfigLab.newInstance(mActivity, getString(R.string.module_appFinance))
        .autoConfigTitle(v);
    DynamicConfigLab.newInstance(mActivity, getString(R.string.module_appFinance))
        .autoConfigVisiblity(v);
    etoffBorrow.setEnabled(false);
    //监听文字改变
    etpoutAmount.addTextChangedListener(watcher());
    etoffBorrow.addTextChangedListener(watcher());

    rgisOffest.setOnCheckedChangeListener(new OnCheckedChangeListener() {

      @Override public void onCheckedChanged(RadioGroup arg0, int arg1) {
        switch (arg1) {
          case R.id.rb_false_offset:
            tag = FALSE;
            etoffBorrow.setText("0.0");
            etoffBorrow.setEnabled(false);
            break;
          case R.id.rb_true_offset:
            tag = TRUE;
            etoffBorrow.setEnabled(true);
            break;

          default:
            break;
        }
      }
    });

    //附件
    mTvExtra = (TextView) v.findViewById(R.id.tv_extra);
    mIvExtra = (ImageView) v.findViewById(R.id.iv_extra);
    mIvExtra.setOnClickListener(new OnClickListener() {

      @Override public void onClick(View v) {
        DialogFragment dialog = ExtraUpLoadDialogFragment.newInstance(mFilePath);

        FragmentManager fm = getActivity().getSupportFragmentManager();
        dialog.setTargetFragment(TravelReimburselFragment.this, REQUEST_ADDEXTRA);
        dialog.show(fm, "");
      }
    });

    /**  选择相关合同、订单、项目   */
    ibcontract.setOnClickListener(new OnClickListener() {

      @Override public void onClick(View arg0) {
        ////				DialogFragment dialog = null;
        ////				dialog = new ContractDialogFragment();
        ////				FragmentManager fm = getActivity().getSupportFragmentManager();
        ////				dialog.setTargetFragment(TravelReimburselFragment.this, REQUEST_CONTRACT);
        ////				dialog.show(fm, "");
        //
        Intent i = new Intent(getActivity(), ContractChoosePagerActivity.class);
        startActivityForResult(i, REQUEST_CONTRACT);
      }
    });

    /** 费用归属分类 */
    ibfownerkindName.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        DialogFragment dialog = new FownerKindDialogFrament();
        FragmentManager fm = getActivity().getSupportFragmentManager();
        dialog.setTargetFragment(TravelReimburselFragment.this, REQUEST_KIND);
        dialog.show(fm, "");
      }
    });
    ibappobjectName.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        //公司费用
        if ("01".equals(fownerkindCode)) {
          DialogFragment dialogFragment =
              AppObjectDialogFragment.newInstance(AppObjectDialogFragment.COMPANY);
          FragmentManager fm = getActivity().getSupportFragmentManager();
          dialogFragment.setTargetFragment(TravelReimburselFragment.this, REQUEST_OBJECT);
          dialogFragment.show(fm, "");
        }
        //部门费用
        if ("02".equals(fownerkindCode)) {
          DialogFragment dialogFragment =
              AppObjectDialogFragment.newInstance(AppObjectDialogFragment.DEPT);
          FragmentManager fm = getActivity().getSupportFragmentManager();
          dialogFragment.setTargetFragment(TravelReimburselFragment.this, REQUEST_OBJECT);
          dialogFragment.show(fm, "");
        }
        //项目费用-项目列表
        if ("03".equals(fownerkindCode)) {
          Intent i = new Intent(getActivity(), ProjectChooseListActivity.class);
          startActivityForResult(i, REQUEST_OBJECT);
        }
        //个人费用
        if ("04".equals(fownerkindCode)) {
          appobjectName = mCurrentUser.getRealName();
          appobjectCode = mCurrentUser.getJobNumber();
          tvappobjectName.setText(appobjectName);
        }
      }
    });
    initData();
    return v;
  }

  protected void initData() {
  }

  protected TextWatcher watcher() {
    return new TextWatcher() {
      @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override public void onTextChanged(CharSequence s, int start, int before, int count) {

        try {
          double poutAmount = 0.0;// 应报销
          double toutAmount = 0.0;//实际报销
          double offborrow = 0.0;
          if (!TextUtils.isEmpty(etpoutAmount.getText().toString())) {
            poutAmount = Double.parseDouble(etpoutAmount.getText().toString());
          }
          if (!TextUtils.isEmpty(etoffBorrow.getText().toString())) {
            offborrow = Double.parseDouble(etoffBorrow.getText().toString());
          }
          if (offborrow > poutAmount) {
            ToastUtil.show("冲抵金额不能大于应报销！");
          } else {
            toutAmount = poutAmount - offborrow;
            ettoutAmount.setText(toutAmount + "");
          }
          etbillAmount.setText(poutAmount + "");
        } catch (NumberFormatException e) {
          e.printStackTrace();
        }
      }

      @Override public void afterTextChanged(Editable s) {

      }
    };
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }

    if (requestCode == REQUEST_KIND && data != null) {
      CustomerDialog kindContent =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      fownerkindName = kindContent.getName();
      fownerkindCode = kindContent.getId();
      tvfownerkindName.setText(fownerkindName);
      tvappobjectName.setText("");
      appobjectCode = "";
      appobjectName = "";
    }
    if (requestCode == REQUEST_OBJECT && data != null) {
      if ("01".equals(fownerkindCode) || "02".equals(fownerkindCode)) {
        CustomerDialog objectContent =
            (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
        appobjectName = objectContent.getName();
        appobjectCode = objectContent.getId();
        tvappobjectName.setText(appobjectName);
      }
      if ("03".equals(fownerkindCode)) {
        ProjectCollectOriginal.ProjectCollectContent objectContent =
            (ProjectCollectOriginal.ProjectCollectContent) data.getSerializableExtra(
                ProjectChooseListFragment.EXTRA_CONTENT);
        appobjectName = objectContent.getProjectName();
        appobjectCode = objectContent.getId();
      }
      tvappobjectName.setText(appobjectName);
    }
    if (requestCode == REQUEST_CONTRACT && data != null) {
      //			CustomerDialog customer = (CustomerDialog) data
      //					.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      //			mContractName=customer.getName();
      //			mContractId=customer.getId();
      //			mContractKind=customer.getJobNo();//合同类别
      //			mContractCode=customer.getMemberCode();//合同编码
      //			tvcontractId.setText(mContractName);//相关合同
      CustomerDialog contractContent =
          (CustomerDialog) data.getSerializableExtra(ContractChoosePagerActivity.EXTRA_CONTRACT);
      type = data.getStringExtra(ContractChoosePagerActivity.EXTRA_TYPE);
      //订单
      if (type.equals(ContractChoosePagerActivity.ORDER)) {
        mOrderName = contractContent.getName();
        mOrderId = contractContent.getId();
        String kindId = contractContent.getJobNo();
        if ("1".equals(kindId)) {
          mOrderType = "out";
        } else if ("2".equals(kindId)) {
          mOrderType = "in";
        }
        mContractPrice = contractContent.getMemberCode();//订单金额

        mContractName = "";
        mContractId = "";
        mContractKind = "";//合同类别
        mContractCode = "";//合同编码

        mProjectName = "";
        mProjectId = "";

        tvcontractId.setText(mOrderName);//订单
      }
      //合同
      if (type.equals(ContractChoosePagerActivity.CONTRACT)) {
        mOrderName = "";
        mOrderId = "";
        mOrderType = "";

        mContractName = contractContent.getName();//合同名称
        mContractId = contractContent.getId();//合同id
        mContractKind = contractContent.getJobNo();//合同类别
        mContractCode = contractContent.getMemberCode();//合同编码
        mContractPrice = contractContent.getDept();//合同金额

        mProjectName = "";
        mProjectId = "";

        tvcontractId.setText(mContractName);//相关合同
      }
      //项目
      if (type.equals(ContractChoosePagerActivity.PROJECT)) {
        mOrderName = "";
        mOrderId = "";
        mOrderType = "";

        mContractName = "";
        mContractId = "";
        mContractKind = "";//合同类别
        mContractCode = "";//合同编码

        mProjectName = contractContent.getName();
        mProjectId = contractContent.getId();
        mContractPrice = contractContent.getJobNo();//项目金额
        tvcontractId.setText(mProjectName);
      }

      return;
    }
    //附件
    if (requestCode == REQUEST_ADDEXTRA) {
      String result = data.getStringExtra(ExtraUpLoadDialogFragment.EXTRA_RESULT);
      if (ExtraUpLoadDialogFragment.VALUE_CLEAR.equalsIgnoreCase(result)) {
        clearExtraFile();
      } else {

        mFilePath = result;
        LogUtil.i("mDocPath===" + mFilePath);
        if (mFilePath != null) {
          mfileName = FileUtil.getFileNameByFilePath(mFilePath);
          //							String fileName = FileUtil.getFileNameByFilePath(mDocPath);
          //							String[] names =fileName.split("\\.");
          //							mfileName =names[names.length-2]+"."+names[names.length-1];
          mTvExtra.setText(mfileName);
        }
      }
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  public void clearExtraFile() {
    mFilePath = "";
    mfileName = "";
    mTvExtra.setText("");
  }
}

